package com.eunion.web.admin.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.eunion.core.common.KvVo;
import com.eunion.core.exception.ProjectException;
import com.eunion.web.admin.entity.AdminRole;
import com.eunion.web.admin.entity.AdminRoleAuth;
import com.eunion.web.admin.repository.AdminRoleAuthRepository;
import com.eunion.web.admin.repository.AdminRoleRepository;
import com.eunion.web.admin.repository.AdminRoleRepositoryCustom;
import com.eunion.web.admin.service.AdminRoleService;
import com.eunion.web.common.base.BaseRepository;
import com.eunion.web.common.base.impl.BaseServiceImpl;

/**
 * @see AdminRole.
 * 
 */
@Service(value="adminRoleService")
@Transactional(propagation = Propagation.REQUIRED,rollbackFor = {Exception.class})
public class AdminRoleServiceImpl extends BaseServiceImpl<AdminRole, String> implements AdminRoleService {

	@Resource
	private AdminRoleRepository adminRoleRepository;

	@Resource
	private AdminRoleAuthRepository adminRoleAuthRepository;

	@Override
	public BaseRepository<AdminRole, String> geBaseRepository() {
		return adminRoleRepository;
	}

	@Override
	public List<AdminRole> findByRoleCodeOrRoleName(String roleCode, String roleName) {
		return adminRoleRepository.findByRoleCodeOrRoleName(roleCode, roleName);
	}

	@Override
	public List<KvVo> findAllRoles() {
		return adminRoleRepository.findAllRoles();
	}

	@Override
	public List<String> fingAllRolesByUsername(String username) {
		return adminRoleRepository.fingAllRolesByUsername(username);
	}

	@Override
	public List<String> fingAllAuthsByRole(String roleCode) {
		return adminRoleRepository.fingAllAuthsByRole(roleCode);
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED,rollbackFor = {Exception.class})
	public int removeRoleAuths(String roleCode, String[] authCodes) {
		Integer sums = adminRoleRepository.removeRoleAuths(roleCode);
		List<AdminRoleAuth> araLists = new ArrayList<AdminRoleAuth>();
		for (String authCode : authCodes) {
			araLists.add(new AdminRoleAuth(authCode,roleCode));
		}
		List<AdminRoleAuth> returnSaves = adminRoleAuthRepository.save(araLists);
		if (sums != null && returnSaves != null) {
			return 1;
		}

		throw new ProjectException("数据更新失败，请检查数据合法性.");
	}

    @Resource
    private AdminRoleRepositoryCustom adminRoleRepositoryCustom;
	
    @Override
    public List<Object[]> groupBySql() {
        return adminRoleRepositoryCustom.groupBySql();
    }

    @Override
    public List<Object[]> groupByHql() {
        return adminRoleRepositoryCustom.groupByHql();
    }

    @Override
    public List<Object[]> groupBySpecification() {
        return adminRoleRepositoryCustom.groupBySpecification();
    }

}
